package com.haiyou.dc.api.controller;


import com.haiyou.common.util.R;
import com.haiyou.common.util.ValidatorUtil;
import com.haiyou.mini.programs.model.WxSessionEntity;
import com.haiyou.mini.programs.model.form.WxLoginForm;
import com.haiyou.mini.programs.service.WxMiniAppService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/open/miniApp/")
@Api(tags = "微信小程序登录")
@Slf4j
public class WxLoginApi {

    @Autowired
    private WxMiniAppService wxMiniAppService;

    /**
     * 小程序登录接口
     * 1、通过wx.login获取code
     * 2、通过getPhoneNumber获取encryptedData，iv
     * 3、发送参数【encryptedData】 、【iv】 、【code】  请求后台解密获取用户手机号
     */
    @ApiOperation(value = "小程序登录接口，发送参数【encryptedData】 、【iv】 、【code】  请求后台解密获取用户手机号")
    @PostMapping("/login")
    public R wxLogin(@RequestBody WxLoginForm wxLoginForm) {
        ValidatorUtil.validateEntity(wxLoginForm);
        WxSessionEntity wxSessionEntity = wxMiniAppService.wxLogin(wxLoginForm.getEncryptedData(), wxLoginForm.getCode(), wxLoginForm.getIv());
        if (wxSessionEntity == null || StringUtils.isEmpty(wxSessionEntity.getPhone())) {
            return R.error(500, "登录失败：解密信息失败，或者获取手机号失败");
        }
        return R.ok(wxSessionEntity);
    }

}
